<template>
  <div ref="chartContainer" style="width: 600px; height: 400px"></div>
</template>

<script>
import { ref, onMounted, watch, reactive } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'EchartsComponent',
  setup() {
    const chartContainer = ref(null)
    const chartInstance = ref(null)
    const state = reactive({
      chartData: {
        // 初始数据，可以从接口获取的数据结构
        categories: [],
        seriesData: []
      }
    })

    // 模拟从接口获取数据
    const fetchData = async () => {
      // 这里可以替换成实际的API请求
      const response = await new Promise((resolve) => {
        setTimeout(() => {
          resolve({
            categories: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            seriesData: [120, 200, 150, 80, 70, 110, 130]
          })
        }, 1000)
      })
      state.chartData = response
    }

    // 初始化Echarts实例
    const initChart = () => {
      if (chartContainer.value) {
        chartInstance.value = echarts.init(chartContainer.value)
        const option = {
          title: {
            text: 'ECharts 示例'
          },
          tooltip: {},
          xAxis: {
            data: state.chartData.categories
          },
          yAxis: {},
          series: [
            {
              name: '销量',
              type: 'bar',
              data: state.chartData.seriesData
            }
          ]
        }
        chartInstance.value.setOption(option)
      }
    }

    // 监听数据变化并更新图表
    watch(
      () => state.chartData,
      (newData) => {
        if (chartInstance.value) {
          chartInstance.value.setOption({
            xAxis: {
              data: newData.categories
            },
            series: [
              {
                data: newData.seriesData
              }
            ]
          })
        }
      },
      { deep: true }
    )

    // 组件挂载时获取数据并初始化图表
    onMounted(() => {
      fetchData()
      initChart()
    })

    // 模拟刷新数据（例如，按钮点击事件）
    const refreshData = async () => {
      await fetchData()
    }

    return {
      chartContainer,
      refreshData // 你可以将这个方法绑定到按钮点击事件上，以手动刷新数据
    }
  }
}
</script>

<style scoped>
/* 你可以根据需要添加样式 */
</style>
